﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JeanFish.Security
{
    /// <summary>
    /// An helper using a specific hash algorithm.
    /// </summary>
    public abstract class HashHelper
    {
        /// <summary>
        /// Get the name of hash algorithm which the helper using.
        /// </summary>
        public abstract string AlgorithmsType { get; }
        /// <summary>
        /// Get the size of hash computed by the hash algorithm.
        /// </summary>
        public abstract int HashSize { get; }
        /// <summary>
        /// Compute the hash for a given binary data.
        /// </summary>
        /// <param name="data">The data in binary</param>
        /// <returns>The hash in binary for the given data</returns>
        public abstract byte[] ComputeHash(byte[] data);
        /// <summary>
        /// Verify the hash for a given data against a existing hash.
        /// </summary>
        /// <param name="data">The data in binary</param>
        /// <param name="hash">The existing hash to be compared to</param>
        /// <returns>If the hash for the given data is equal to the existing hash, return true; otherwise, return false</returns>
        public virtual bool VerifyHash(byte[] data, byte[] hash)
        {
            if (data == null)
                throw new ArgumentNullException("data");
            if (hash == null)
                throw new ArgumentNullException("hash");
            var result = ComputeHash(data);
            if (this.HashSize>>3 != result.Length || this.HashSize>>3 != hash.Length) return false;
            string v1 = Convert.ToBase64String(result);
            string v2 = Convert.ToBase64String(hash);
            return v1 == v2;
        }
    }
}